//
//  OneViewController.m
//  phoneTool
//
//  Created by HappyMilk 02 on 2017/7/27.
//  Copyright © 2017年 tomi. All rights reserved.
//

#import "OneViewController.h"
#import "AFNetworking.h"
#import "NewsViewCell.h"
#import "LongImageView.h"
#import "MJRefresh.h"
#import "LoginHeader.h"
//#import "MJLocaStorage.h"
#import "DiscoverLeanCloudTableViewCell.h"
#import "WebViewController.h"
#import "GADTableViewCell.h"

@interface OneViewController ()<UITableViewDelegate,UITableViewDataSource,NewsViewCellDelegate>{
    
    NSString * m_currentTimestamp;
}

@property (weak, nonatomic) IBOutlet UITableView *tabelView;

@property (nonatomic ,strong) NSMutableArray *listArray;


@end

@implementation OneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _listArray = [NSMutableArray array];
    m_currentTimestamp = @"0";
    // Do any additional setup after loading the view.
    
    
    if (IS_CHINESE) {
        [self addHeader];
        [self.tabelView.mj_header beginRefreshing];
    }else{
        [self getLeanCloudListData];
    }
    
}
- (void)addHeader{
    
    self.tabelView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        m_currentTimestamp = @"0";
        [self getBaisiListData];
    }];
    self.tabelView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self getBaisiListData];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //NSString * cellIdentifier = [NSString stringWithFormat:@"%ld-%ld",indexPath.section,indexPath.row];
    
    if (IS_CHINESE) {
        if ([[_listArray objectAtIndex:indexPath.row] isKindOfClass:[GADTableViewCell class]]) {
            GADTableViewCell *cell = (GADTableViewCell *)[_listArray objectAtIndex:indexPath.row];
            return cell;
        }else{
            static NSString *cellIdentifier = @"NewsViewCell";
            NSDictionary *dic = _listArray[indexPath.row];
            NewsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"NewsViewCell" owner:nil options:nil] lastObject];
            }
            cell.delegate = self;
            cell.listDic = dic;
            return cell;
        }
        
    }else{
        static NSString *cellIdentifier = @"DiscoverLeanCloudTableViewCell";
        NSDictionary *dic = _listArray[indexPath.row];
        DiscoverLeanCloudTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DiscoverLeanCloudTableViewCell" owner:nil options:nil] lastObject];
        }
        [cell setup:dic];
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[_listArray objectAtIndex:indexPath.row] isKindOfClass:[GADTableViewCell class]]) {
        return IS_IPAD?600:380;
    }
    return IS_IPAD?400:300;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = _listArray[indexPath.row];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[DiscoverLeanCloudTableViewCell class]]) {
        VC_INIT_WITH_STORYBOARD(news, WebViewController, vc)
        vc.webUrl = [dic objectForKey:@"webUrl"];vc.nav_color = _nav_color;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//NewsViewCellDelegate
- (void)showContentsWithData:(NSData *)data andIsGif:(BOOL)isGif{
    [[AdLibrary stander] showAd];
    [LongImageView showInWindow:data isGif:isGif];
}

- (void)getLeanCloudListData{
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Technology" ofType:@"plist"];
    NSMutableArray *muarr = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    self.listArray = muarr;
    [self.tabelView reloadData];
}

- (void)getBaisiListData{
    
    NSString *url = [NSString stringWithFormat:@"http://s.budejie.com/topic/list/jingxuan/1/bs0315-iphone-4.5.6/%@-20.json",m_currentTimestamp];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
    [manager GET:url parameters:@"" progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSMutableArray *muarr_now = [NSMutableArray array];
        NSMutableArray *muarr = [dic objectForKey:@"list"];
        for (int i=0; i<muarr.count; i++) {
            NSDictionary *listDic = muarr[i];
            NSString *type = [listDic objectForKey:@"type"];
            if ([type isEqualToString:@"image"] || [type isEqualToString:@"video"] || [type isEqualToString:@"gif"]) {
                if (i%3==0 && i!=0) {
                    GADTableViewCell *cell = [[GADTableViewCell alloc] init];
                    [cell setup:self];
                    [muarr_now addObject:cell];
                }
                [muarr_now addObject:listDic];
            }
        }
   
        if ([m_currentTimestamp isEqualToString:@"0"]) {
            self.listArray = muarr_now;
        }else{
            [self.listArray addObjectsFromArray:muarr_now];
        }

        [self.tabelView.mj_header endRefreshing];
        [self.tabelView.mj_footer endRefreshing];
        
        [self.tabelView reloadData];
        m_currentTimestamp = [dic[@"info"][@"np"] stringValue];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//AVQuery *query = [AVQuery queryWithClassName:@"DiscoverCategoryItem"];
//[query whereKey:@"category_title" equalTo:@"Wi-Fi"];//Technology News Wi-Fi
//
//[query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
//    
//    if (objects != nil && objects.count > 0) {
//        //link title cover
//        
//        
//        [_listArray addObjectsFromArray:objects];
//        [self.tabelView reloadData];
//        
//        NSMutableArray *muarr = [NSMutableArray array];
//        for (AVObject *object in objects) {
//            NSDictionary *dic = @{@"webUrl":[object objectForKey:@"link"],@"title":[object objectForKey:@"title"],@"imgUrl":[object objectForKey:@"cover"]};
//            [muarr addObject:dic];
//        }
//        [MJLocaStorage saveArrayFile:[muarr copy] AndFileName:@"wifi"];
//        
//        
//    }
//}];

@end
